package org.xyl.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xyl.config.DiagnosisConfig;
import org.xyl.model.DeviceStatus;
import org.xyl.service.DeviceService;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 设备服务实现
 */
@Service
public class DeviceServiceImpl implements DeviceService {
    
    private static final Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);
    
    @Autowired
    private DiagnosisConfig diagnosisConfig;
    
    private final Random random = new Random();
    
    @Override
    public DeviceStatus getDeviceStatus(String deviceId) {
        logger.info("获取设备状态: {}", deviceId);
        
        // 模拟设备状态数据
        DeviceStatus status = new DeviceStatus();
        status.setDeviceId(deviceId);
        status.setDeviceType("ESL-" + (deviceId.hashCode() % 200 + 100));
        status.setFirmwareVersion("V1." + (deviceId.hashCode() % 5 + 1) + "." + (deviceId.hashCode() % 10 + 1));
        status.setBatteryVoltage(2.8 + random.nextDouble() * 0.6); // 2.8-3.4V
        status.setSignalStrength(-90 - random.nextInt(30)); // -90 to -120 dBm
        status.setTemperature(20 + random.nextInt(15)); // 20-35°C
        status.setRefreshCount(random.nextInt(1000) + 100);
        status.setLastHeartbeatTime(LocalDateTime.now().minus(random.nextInt(60), ChronoUnit.MINUTES));
        status.setNetworkType(random.nextBoolean() ? "4G" : "NB-IoT");
        status.setOnline(random.nextDouble() > 0.1); // 90%概率在线
        
        return status;
    }
    
    @Override
    public List<String> getDeviceLogs(String deviceId, int days) {
        logger.info("获取设备日志: {}, 最近{}天", deviceId, days);
        
        List<String> logs = new ArrayList<>();
        String[] logTemplates = {
            "[{}] INFO: 设备正常启动，固件版本：{}",
            "[{}] INFO: 成功刷新屏幕内容",
            "[{}] WARN: 电池电压偏低: {:.2f}V",
            "[{}] WARN: 信号强度较弱: {} dBm",
            "[{}] ERROR: 网络连接失败，重试中...",
            "[{}] ERROR: 屏幕刷新超时",
            "[{}] INFO: 成功连接到基站: {}",
            "[{}] INFO: 接收到刷新指令，开始处理",
            "[{}] INFO: 数据同步完成，共{}条记录",
            "[{}] WARN: 存储空间不足，清理缓存"
        };
        
        // 生成模拟日志
        int logCount = random.nextInt(50) + 10;
        for (int i = 0; i < logCount; i++) {
            LocalDateTime logTime = LocalDateTime.now().minus(random.nextInt(days * 24 * 60), ChronoUnit.MINUTES);
            String logTimeStr = logTime.toString().replace('T', ' ').substring(0, 19);
            
            String template = logTemplates[random.nextInt(logTemplates.length)];
            String log;
            
            switch (template) {
                case "[{}] INFO: 设备正常启动，固件版本：{}":
                    log = String.format(template, logTimeStr, "V1.5.2");
                    break;
                case "[{}] WARN: 电池电压偏低: {:.2f}V":
                    log = String.format(template, logTimeStr, 2.7 + random.nextDouble() * 0.3);
                    break;
                case "[{}] WARN: 信号强度较弱: {} dBm":
                    log = String.format(template, logTimeStr, -110 - random.nextInt(20));
                    break;
                case "[{}] INFO: 成功连接到基站: {}":
                    log = String.format(template, logTimeStr, "基站-" + (random.nextInt(1000) + 1000));
                    break;
                case "[{}] INFO: 数据同步完成，共{}条记录":
                    log = String.format(template, logTimeStr, random.nextInt(100) + 1);
                    break;
                default:
                    log = String.format(template, logTimeStr);
                    break;
            }
            
            logs.add(log);
        }
        
        // 按时间排序（从旧到新）
        logs.sort(String::compareTo);
        return logs;
    }
    
    @Override
    public List<String> getDeviceHistoryIssues(String deviceId) {
        logger.info("获取设备历史故障记录: {}", deviceId);
        
        List<String> issues = new ArrayList<>();
        String[] issueTemplates = {
            "[2025-10-15] 电池耗电过快，建议升级固件到V1.5.1",
            "[2025-10-10] 信号不稳定，调整了安装位置",
            "[2025-09-28] 屏幕显示异常，重置设备后恢复正常",
            "[2025-09-15] 网络连接失败，SIM卡接触不良",
            "[2025-09-01] 设备离线，手动重启后恢复"
        };
        
        // 随机选择1-3个历史故障
        int issueCount = random.nextInt(3) + 1;
        for (int i = 0; i < issueCount; i++) {
            int index = random.nextInt(issueTemplates.length);
            if (!issues.contains(issueTemplates[index])) {
                issues.add(issueTemplates[index]);
            }
        }
        
        return issues;
    }
}